package com.itheima.leyou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.leyou.common.dto.PageDTO;
import com.itheima.leyou.po.CategoryBrand;
import com.itheima.leyou.mapper.BrandMapper;
import com.itheima.leyou.service.BrandService;
import com.itheima.leyou.service.CategoryBrandService;
import com.leyou.item.dto.BrandDTO;
import com.itheima.leyou.po.Brand;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper,Brand> implements BrandService {
    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public BrandDTO queryBrandById(Long id) {
      return baseMapper.queryBrandById((id));

    }


    @Override
    public List<BrandDTO> queryBrandByIds(List<Long> ids) {
        List<Brand> brandList = this.listByIds(ids);
       return BrandDTO.convertEntityList(brandList);
    }

    @Override
    public List<BrandDTO> queryBrandByCategoryId(Long id) {
        //得到所有的中间表信息集合
        List<CategoryBrand> categoryBrands = categoryBrandService
                .query()
                .eq("category_id", id)
                .list();
        //得到所有的品牌id集合
        List<Long> brands = categoryBrands.stream()
                .map(CategoryBrand::getBrandId)
                .collect(Collectors.toList());
        //判空,处理不得当，待完善？？？？
        if(brands==null||brands.size()==0){
            return null;

        }
        //查询到品牌ids对应的信息
        return this.queryBrandByIds(brands);

    }


//    @Override
//    @Transactional
//    public Boolean addOrUpdate(BrandVO brandVO) {
//        //新增品牌对应的分类信息
//        Long bid = brandVO.getId();
//        if(StringUtils.isNotBlank(String.valueOf(bid))){
//            //编辑操作,删除中间表对应的分类id
//            categoryBrandService.removeById(bid);
//            if(StringUtils.isNotBlank(brandVO.getImage())){
//                //图片存在
//                baseMapper.deleteByBrandId(bid);
//            }
//        }
//        //新增品牌
//        Boolean   flag = this.saveOrUpdate(brandVO);
//        Long id = brandVO.getId();
//        List<Long> categoryIds = brandVO.getCategoryIds();
//            if(categoryIds!=null||categoryIds.size()>0){
//                //执行添加操作到中间表
//                for (Long categoryId : categoryIds) {
//                    baseMapper.add(id,categoryId);
//                }
//            }
//
//        return flag;
//    }


    @Override
    @Transactional
    public void addOrUpdate(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        //新增品牌表
        this.save(brand);
        //添加中间表信息
        categoryAndBrand(brandDTO.getCategoryIds(), brand.getId());
    }


    private void categoryAndBrand(List<Long> categoryIds, Long bid) {
        List<CategoryBrand> list = categoryIds
                .stream()
                .map(cid -> CategoryBrand.of(cid, bid))
                .collect(Collectors.toList());
        categoryBrandService.saveBatch(list);
    }


    /**
     * 物理删除，现在不会处理异常信息，表中，没有逻辑删除相关的信息
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Boolean removeByPid(Long id) {
        //删除品牌表信息
         this.removeById(id);
        //删除中间表信息
        boolean flag = categoryBrandService.remove(
                new QueryWrapper<CategoryBrand>().eq("brand_id",id));
        return flag;
    }

    @Override
    public PageDTO<BrandDTO> findPage(Integer page, Integer rows, String key) {
        //普通的分页查询
        Page<Brand> info = new Page<>(page, rows);
        //条件搜索，条件可以有多个
        Page<Brand> page1 = page(info, new QueryWrapper<Brand>()
                .like(StringUtils.isNoneBlank(key), "name", key)
                .or()
                //select * from tb_brand where letter = null limit 1,10;
                // 要加上搜索的条件，如果不加默认的是null,一定要注意
                .eq(StringUtils.isNoneBlank(key), "letter", key));

        return new PageDTO<>(page1.getTotal(), page1.getPages(),
                BrandDTO.convertEntityList(page1.getRecords()));
    }


    @Override
    public void updateBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        //修改品牌表信息
        this.updateById(brand);
        //解除中间表之间的逻辑关系
        categoryBrandService.remove(new QueryWrapper<CategoryBrand>
                ().eq("brand_id",brand.getId()));
        //然后在进行添加中间表操作
        categoryAndBrand(brandDTO.getCategoryIds(), brand.getId());
    }
}
